import React from 'react';
import {
  Modal,
  Button,
  Form,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Switch,
  TimePicker,
  Tooltip,
} from 'antd';
import styles from './index.less';
import moment from 'moment';

const Item = Form.Item;
const Option = Select.Option;

@Form.create()
class Components extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      type: 'domainGroupIds',
      formatData: {
        id: null,
      },
    };
  }
  /**
   * 提交表单到父组件
   */
  onOk = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.checkAddress = values.checkAddress.join(';');
        values.forwardName && (values.forwardName = values.forwardName.join(','));
        values.serverList = values.serverList.join(',');
        values.openState = values.openState ? 1 : 0;
        values.defaultForward = values.defaultForward ? 1 : 0;
        values.optimization = 0;
        values.startDate = moment(values.startDate).format('HH:mm:ss');
        values.endDate = moment(values.endDate).format('HH:mm:ss');
        this.props.submit(values);
      }
    });
  };

  typeChange = value => {
    this.setState({
      type: value,
    });
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    if ((nextProps.formatData && nextProps.formatData.id) !== prevState.formatData.id) {
      let type = '';
      if (nextProps.formatData.domainGroupIds.length > 0) {
        type = 'domainGroupIds';
      } else {
        type = 'forwardName';
      }
      return {
        type,
      };
    } else {
      return null;
    }
  }

  clear = () => {
    this.props.form.resetFields();
  };

  render() {
    const {
      visible,
      formatData,
      close,
      list,
      form: { getFieldDecorator },
    } = this.props;
    const { type } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };
    return (
      <Modal
        title="配置DNS转发"
        afterClose={this.clear}
        visible={visible}
        onCancel={close}
        okText="确定"
        cancelText="取消"
        destroyOnClose={true}
        onOk={this.onOk}
      >
        <div className={styles.formWrap}>
          <Form>
            <Item
              {...formItemLayout}
              label={
                <Select
                  onChange={this.typeChange}
                  size="small"
                  value={type}
                  style={{ width: '70%' }}
                >
                  {[
                    { name: '转发域名', key: 'forwardName' },
                    { name: '选择域名组', key: 'domainGroupIds' },
                  ].map(item => (
                    <Option key={item.key} value={item.key}>
                      {item.name}
                    </Option>
                  ))}
                </Select>
              }
            >
              {getFieldDecorator(type, {
                rules: [{ required: true, message: '不能为空' }],
                initialValue: formatData
                  ? type === 'domainGroupIds'
                    ? formatData.domainGroupIds
                    : formatData.forwardName.split(',')
                  : [],
              })(
                <Select
                  mode={type === 'domainGroupIds' ? 'multiple' : 'tags'}
                  style={{ width: '100%' }}
                  tokenSeparators={[',']}
                >
                  {type === 'domainGroupIds'
                    ? list.map((item, index) => (
                        <Option value={item.id} key={item.id}>
                          <Tooltip placement="topLeft" title={item.groupTitle}>
                            <span> {item.groupTitle}</span>
                          </Tooltip>
                        </Option>
                      ))
                    : [].map((item, index) => (
                        <Option value={item} key={item}>
                          {item}
                        </Option>
                      ))}
                </Select>
              )}
            </Item>
            <Item {...formItemLayout} label="服务列表">
              {getFieldDecorator('serverList', {
                rules: [{ required: true, message: '不能为空' }],
                initialValue: formatData ? formatData.serverList.split(',') : [],
              })(
                <Select mode="tags" style={{ width: '100%' }} tokenSeparators={[',']}>
                  {[].map((item, index) => (
                    <Option value={item.id} key={index}>
                      {item.id}
                    </Option>
                  ))}
                </Select>
              )}
            </Item>
            <Item {...formItemLayout} label="转发类型">
              {getFieldDecorator('type', {
                rules: [{ required: true, message: '不能为空' }],
                initialValue: formatData && formatData.type,
              })(
                <Select>
                  {['only'].map(item => (
                    <Option value={item} key={item}>
                      {item}
                    </Option>
                  ))}
                </Select>
              )}
            </Item>
            <Item {...formItemLayout} label="健康检查地址">
              {getFieldDecorator('checkAddress', {
                rules: [{ required: true, message: '不能为空' }],
                initialValue: formatData ? formatData.checkAddress.split(';') : [],
              })(
                <Select mode="tags" style={{ width: '100%' }} tokenSeparators={[',']}>
                  {[].map((item, index) => (
                    <Option value={item.id} key={index}>
                      {item.id}
                    </Option>
                  ))}
                </Select>
              )}
            </Item>
            <Item {...formItemLayout} label="健康检查类型">
              {getFieldDecorator('checkType', {
                rules: [{ required: true, message: '不能为空' }],
                initialValue: formatData && formatData.checkType,
              })(
                <Select>
                  {['dns'].map(item => (
                    <Option value={item} key={item}>
                      {item}
                    </Option>
                  ))}
                </Select>
              )}
            </Item>
            <Item {...formItemLayout} label="健康检查间隔">
              {getFieldDecorator('checkInterval', {
                rules: [{ required: true, message: '不能为空' }],
                initialValue: (formatData && formatData.checkInterval) ? formatData.checkInterval : 10,
              })(<InputNumber style={{width:"200px"}} min={0} />)}
              <span> 秒</span>
            </Item>
            <Item {...formItemLayout} label="启用开始时间">
              {getFieldDecorator('startDate', {
                // rules: [{ required: true, message: '不能为空' }],
                initialValue: formatData && moment(formatData.startDate, 'HH:mm:ss'),
              })(<TimePicker placeholder="开始时间" style={{ width: '100%' }} />)}
            </Item>
            <Item {...formItemLayout} label="启用结束时间">
              {getFieldDecorator('endDate', {
                // rules: [{ required: true, message: '不能为空' }],
                initialValue: formatData && moment(formatData.endDate, 'HH:mm:ss'),
              })(<TimePicker placeholder="结束时间" style={{ width: '100%' }} />)}
            </Item>
            <Item {...formItemLayout} label="启用状态">
              {getFieldDecorator('openState', {
                valuePropName: 'checked',
                initialValue: formatData && formatData.openState ? true : false,
              })(<Switch checkedChildren="开" unCheckedChildren="关" />)}
            </Item>
            <Item {...formItemLayout} label="默认转发">
              {getFieldDecorator('defaultForward', {
                valuePropName: 'checked',
                initialValue: formatData && formatData.defaultForward ? true : false,
              })(<Switch checkedChildren="开" unCheckedChildren="关" />)}
            </Item>
          </Form>
        </div>
      </Modal>
    );
  }
}

export default Components;
